<?php
/**
 * This class provides static methods for relating type of object properties with column types of database's tables.<br/>
 * Originally, phporm manage the relation based on naming convention of object property's name.<br/>
 * You can modify this class when you want to use other naming convention or other method for managing the relation.
 * 
 * @package lib.famteam.phporm
 * @author polikeiji
 *
 */
class FieldLibrary {
	
	public static $COLUMN_TYPE_MAP = array(
			"id" => "bigint(20) not NULL primary key AUTO_INCREMENT", 
			"s" => "varchar(255)",
			"x" => "text",
			"d" => "bigint(20)",
			"i" => "int(11)",
			"b" => "tinyint(1)",
			"t" => "timestamp");

	/**
	 * Check whether the type of the object property is appropriate.<br/>
	 * Originally, a prefix of a property name represents column type of database table,
	 * and we can use the 5 prefixes; id (unique key), i (integer), d (double), t (datetime), and b (bool).<br/>
	 * 
	 * @param str $fieldName
	 * @param mixed $fieldValue
	 * @return bool
	 */
	public static function typeCheck($fieldName, $fieldValue) {
		$fieldTypeString = $fieldName == "id" ?
			$fieldName :
			substr($fieldName, 0, 1);
		if ($fieldTypeString == "id" ||
			$fieldTypeString == "i" ||
			$fieldTypeString == "d" ||
			$fieldTypeString == "t" ||
			$fieldTypeString == "b") {
			return $fieldValue === null ||
				is_numeric($fieldValue);	
		}
		else if ($fieldTypeString == "s" || $fieldTypeString == "x") {
			return $fieldValue === null ||
				is_string($fieldValue);
		}
	}
	
	/**
	 * 
	 * @param str $fieldName
	 * @return bool
	 */
	public static function isString($fieldName) {
		return FieldLibrary::getFieldTypeString($fieldName) == "s" ||
			FieldLibrary::getFieldTypeString($fieldName) == "x";
	}
	
	/**
	 * 
	 * @param str $fieldName
	 * @return bool
	 */
	public static function isTimestamp($fieldName) {
		return FieldLibrary::getFieldTypeString($fieldName) == "t";
	}
	
	/**
	 * 
	 * @param str $fieldName
	 * @return bool
	 */
	public static function getFieldTypeString($fieldName) {
		return $fieldName == "id" ?
			$fieldName :
			substr($fieldName, 0, 1);
	}
	
	/**
	 * Check whether the property is required or not.<br/>
	 * r after the prefix for representing the column type indicate that this property is required.
	 * 
	 * @param str $fieldName
	 * @return bool
	 */
	public static function isRequiredField($fieldName) {
		return substr($fieldName, 1, 1) == "r";
	}
	
	public static function getColumnType($propertyName) {
		$columnTypeString = $propertyName == "id" ?
			$propertyName :
			substr($propertyName, 0, 1);
		return FieldLibrary::$COLUMN_TYPE_MAP[$columnTypeString];
	}
	
	
}
?>